# _*_ coding : utf-8 _*_
# @Time : 2025/4/6 16:07
# @Author : 梁满仓
# @File : stock_15_min_hist_data
# @Project : stock_of_donnie_day_day_up


import requests
import pandas as pd
from datetime import datetime
import time
from tqdm import tqdm
import akshare as ak

#save_path = 'stock_data/Unadjusted/'
#save_path = 'stock_data/15_min/Forward_Adjusted/'
save_path = 'stock_data/15_min/Backward_Adjusted/'


def get_eastmoney_15min_data(stock_code, adjust='hfq'):
    """
    从东方财富获取股票15分钟数据（支持后复权）

    参数:
    stock_code: 6位股票代码，如'600000'或'000001'
    adjust: 复权类型，可选:
        - None或'': 不复权
        - 'qfq': 前复权
        - 'hfq': 后复权(默认)

    返回:
    DataFrame包含15分钟K线数据
    """
    # 市场判断 (1=上海, 0=深圳)
    market = "1" if stock_code.startswith("6") else "0"

    # 复权参数 (0=不复权, 1=前复权, 2=后复权)
    adjust_map = {'': 0, 'qfq': 1, 'hfq': 2}
    fqt = adjust_map.get(adjust.lower() if adjust else '', 2)

    url = "http://push2his.eastmoney.com/api/qt/stock/kline/get"
    params = {
        "secid": f"{market}.{stock_code}",
        "fields1": "f1,f2,f3,f4,f5,f6",  # 扩展字段
        "fields2": "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61",  # 更多数据字段
        "klt": 15,  # 15分钟线
        "fqt": fqt,  # 复权类型
        "beg": "0",  # 开始日期(0表示最早)
        "end": "20500000",  # 结束日期(未来日期表示取全部)
        "lmt": "10000",  # 最大数据条数
    }

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Referer": "http://quote.eastmoney.com/",
    }

    try:
        response = requests.get(url, params=params, headers=headers, timeout=10)
        response.raise_for_status()
        json_data = response.json()

        if json_data.get("data") is None:
            print(f"未获取到数据，返回结果: {json_data}")
            return pd.DataFrame()

        klines = json_data["data"].get("klines", [])

        result = []
        for item in klines:
            parts = item.split(",")
            if len(parts) >= 11:  # 确保有足够的数据字段
                result.append({
                    "datetime": parts[0],  # 时间: 2023-01-01 09:45
                    "open": float(parts[1]),  # 开盘价
                    "close": float(parts[2]),  # 收盘价
                    "high": float(parts[3]),  # 最高价
                    "low": float(parts[4]),  # 最低价
                    "volume": int(parts[5]),  # 成交量(手)
                    "amount": float(parts[6]),  # 成交额(元)
                    "amplitude": float(parts[7]),  # 振幅%
                    "change_percent": float(parts[8]),  # 涨跌幅%
                    "change_amount": float(parts[9]),  # 涨跌额
                    "turnover_rate": float(parts[10]) if parts[10] else 0.0,  # 换手率%
                })

        df = pd.DataFrame(result)

        # 转换时间格式
        if not df.empty:
            df['datetime'] = pd.to_datetime(df['datetime'])
            df = df.sort_values('datetime').reset_index(drop=True)

            # 添加时间相关特征
            df['date'] = df['datetime'].dt.date
            df['time'] = df['datetime'].dt.time
            df['day_of_week'] = df['datetime'].dt.dayofweek + 1  # 1-7表示周一到周日

        return df

    except Exception as e:
        print(f"获取股票 {stock_code} 15分钟数据失败: {str(e)}")
        return pd.DataFrame()



def get_multiple_stocks_15min_data(stock_list, adjust='hfq', delay=1):
    """
    批量获取多只股票5分钟数据

    参数:
    stock_list: 股票代码列表，如['600000', '000001']
    adjust: 复权类型
    delay: 请求间隔(秒)

    返回:
    包含所有股票数据的DataFrame
    """
    all_data = []
    for code in tqdm(stock_list, desc="正在获取股票数据"):
        df = get_eastmoney_15min_data(code, adjust=adjust)
        if not df.empty:
            all_data.append(df)
        time.sleep(delay)  # 避免请求过于频繁

    if all_data:
        return pd.concat(all_data, ignore_index=True)
    return pd.DataFrame()



# 使用示例
if __name__ == "__main__":
    # 获取 A 股所有上市公司的代码和名称
    stock_info_a_code_name_df = ak.stock_info_a_code_name()

    # 循环获取每一家公司的股票数据并保存
    for index, row in stock_info_a_code_name_df.iterrows():
        stock_code = row['code']
        stock_name = row['name']
        # 组合文件名，例如：贵州茅台 600519.SH.csv
        # file_name = f"{stock_code}_{stock_name}.csv"
        file_name = f"{stock_code}.csv"

        try:
            # 单只股票示例
            print("获取单只股票15分钟数据...")
            df_single = get_eastmoney_15min_data(stock_code, adjust='hfq')
            if not df_single.empty:
                print(f"获取到 {len(df_single)} 条15分钟数据")
                print(df_single.head())
                # 保存到CSV
                df_single.to_csv(save_path + file_name, index=False)
                print(f"{index}-{stock_name}（{stock_code}）的数据已成功保存到 {file_name}")
            else:
                print("未能获取数据")

            time.sleep(1)  # 避免请求过于频繁

        except Exception as e:
            print(f"获取 {index}-{stock_name}（{stock_code}）的数据时出现错误：{str(e)}")

    '''
    stock_code = "600519"
    # 获取后复权数据
    df_hfq = get_eastmoney_15min_data("600000", adjust='hfq')
    print("后复权数据示例:")
    print(df_hfq.head())
    df_hfq.to_csv(f"{stock_code}_hfq.csv", index=False)

    stock_code = "000063"
    # 获取不复权数据
    df_raw = get_eastmoney_15min_data(stock_code, adjust='')
    print("\n不复权数据示例:")
    print(df_raw.head())
    df_raw.to_csv(f"{stock_code}_nfq.csv", index=False)
    '''

    print('ok!')
